﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Outlook.WorkItems.Extension.Manager.TeamProjectManager
{
    /// <summary>
    /// Store information about Work Item Type to create and mapping between work item fields and mail message fields
    /// </summary>
    public class WorkItemMapping
    {
        public WorkItemMapping()
        {
            Name = "";
        }
        /// <summary>
        /// List of Mapping Items
        /// </summary>
        public List<MappingField> MappingFields { get; set; }
        /// <summary>
        /// Work Item Type
        /// </summary>
        public string WorkItemType { get; set; }

        public string Name { get; set; }
        /// <summary>
        /// Serialize object instance in XML
        /// </summary>
        /// <returns></returns>
        public XNode SerializeWorkItemMapping()
        {
            return new XElement("WorkItemMapping",
                            new XAttribute("name", Name),
                            new XAttribute("workItemType", WorkItemType),
                            new XElement("MappingFields",
                                from mf in this.MappingFields
                                select new XElement("MappingField",
                                            new XAttribute("wiField", mf.WiFieldName),
                                            new XAttribute("messageField", mf.MessageFieldName),
                                            new XAttribute("staticValue", mf.StaticValue))));
        }

        /// <summary>
        /// Deserialize XML specified in object instance
        /// </summary>
        /// <param name="xmapping"></param>
        public void DeserializeWorkItemMapping(XElement xmapping)
        {
            if (xmapping == null)
                return;

            WorkItemType = xmapping.Attribute("workItemType").Value;
            MappingFields = (from mf in xmapping.Element("MappingFields").Elements()
                                 select new MappingField()
                                 {
                                     WiFieldName = mf.Attribute("wiField").Value,
                                     MessageFieldName = mf.Attribute("messageField").Value,
                                     StaticValue = mf.Attribute("staticValue").Value
                                 }).ToList();
            var nameAttribute = xmapping.Attributes("name").FirstOrDefault();
            if (nameAttribute != null)
                Name = nameAttribute.Value;
        }
    }
}
